package com.example.im.server.im

import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import cc.vv.lkbasecomponent.util.LKSPUtil
import cc.vv.lkbasecomponent.util.LKStringUtil
import cc.vv.lkimcomponent.lkim.bean.LKIMConversation
import cc.vv.lkimcomponent.lkim.bean.LKIMMessage
import cc.vv.lkimcomponent.lkim.bean.body.LKIMTxtBody
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMChatType
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMDirect
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMStatus
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMType
import cc.vv.lkimcomponent.lkim.inter.LKIMConversationInter
import cc.vv.lkimcomponent.lkim.operate.LKIMGet
import cc.vv.lkimcomponent.view.emoji.ParseEmojiOperate
import com.example.baselibrary.R
import com.example.baselibrary.db.dao.AccountDao
import com.example.mvp.view.DialogListView
import com.example.im.IMConversationOperate
import com.example.util.finallist.*
import java.util.*

/**
 * Im相关逻辑
 * @author  chaohaipeng  on 2018/7/24.
 */
class IMChatService {
    private object mHolder {
        val instance = IMChatService()
    }
    companion object {
        fun getInstance(): IMChatService {
            return mHolder.instance
        }
    }

        /**
         * 初始化会话列表数据
         *
         * @param isShowSecurity    是否显示密聊
         * @param conversationInter 操作回调
         */
        fun initConversation(isShowSecurity: Boolean, conversationInter: ConversationInter?) {
            if (null == conversationInter) return
            Thread(Runnable {
                LKIMGet.getInstance().getConversation(object : LKIMConversationInter {
                    override fun success(lkimConversations: List<LKIMConversation>) {
                        val conversations = ArrayList<LKIMConversation>()
                        var securityConversation: MutableList<LKIMConversation>? = null
                        if (isShowSecurity) {
                            for (lkimConversation in lkimConversations) {
                                if (null != lkimConversation.lastLKIMMessage) {
                                    conversations.add(lkimConversation)
                                } else {
                                    val draftText = lkimConversation.getAttribute(IMExtKey.EXTKEY_DRAFTTEXT, "")
                                    if (!TextUtils.isEmpty(draftText.trim { it <= ' ' })) {
                                        conversations.add(lkimConversation)
                                    }
                                }
                            }
                        } else if (!lkimConversations.isEmpty()) {
                            for (lkimConversation in lkimConversations) {
                                if (null != lkimConversation.lastLKIMMessage) {
                                    conversations.add(lkimConversation)
                                } else {
                                    val draftText = lkimConversation.getAttribute(IMExtKey.EXTKEY_DRAFTTEXT, "")
                                    if (!TextUtils.isEmpty(draftText.trim { it <= ' ' })) {
                                        conversations.add(lkimConversation)
                                    }
                                }
                            }
                        }
                        IMConversationOperate.getInstance().initDNDExt(conversations)
                        IMConversationOperate.getInstance().initTopExt(conversations)
                        conversationInter!!.success(conversations)
                        if (securityConversation != null) {
                            var unreadCount = 0
                            for (conversation in securityConversation) {
                                if (conversation != null) {
                                    unreadCount += conversation.unRreadMsgCount
                                }
                            }
                            conversationInter!!.privateMessageCount(unreadCount)
                        }
                    }

                    override fun faile() {
                        conversationInter!!.faile()
                    }
                })
            }).start()
        }

    /**
     * 初始化会话列表弹窗列表数据
     *
     * @return 列表数据
     */
    fun initIMFDialog(isStick: Boolean, isSecurity: Boolean): List<DialogListView.DialogListObj> {
        val dialogListObjs = ArrayList<DialogListView.DialogListObj>()
        if (!isSecurity) {
            if (isStick) {
                dialogListObjs.add(DialogListView.DialogListObj(SkKey.BTKEY_INT_0, LKStringUtil.getString(R.string.string_im_stick_cancel)))
            } else {
                dialogListObjs.add(DialogListView.DialogListObj(SkKey.BTKEY_INT_0, LKStringUtil.getString(R.string.string_im_stick)))
            }
        }
        dialogListObjs.add(DialogListView.DialogListObj(SkKey.BTKEY_INT_1, LKStringUtil.getString(R.string.string_im_delete)))
        return dialogListObjs
    }
    /**
     * 初始化会话列表显示文本
     *
     * @param imConversation
     * @return
     */
    fun initShowText(imConversation: LKIMConversation?): SpannableString {
        if (null == imConversation) return SpannableString("")
        var showTxt = ""
        val imMessage = imConversation.lastLKIMMessage
        if (null != imMessage && !imMessage.isNull) {
            val messageType = imMessage.getAttribute(IMExtKey.EXTKEY_MESSAGETYPE, SkKey.BTKEY_String_0)
            if (!TextUtils.equals(SkKey.BTKEY_String_0, messageType)) {
                if (LKIMChatType.GroupChat == imConversation.lkimChatType) {
                    val isAtMe = imConversation.getAttribute(IMExtKey.EXTKEY_ISATME, SkKey.BTKEY_String_0)
                    if (TextUtils.equals(SkKey.BTKEY_String_1, isAtMe)) {//@
                        showTxt = String.format(Locale.CHINESE, "%s ", LKStringUtil.getString(R.string.string_im_specialRemind))
                    } else {//特别关注
                    }
                    if (LKIMDirect.RECEIVE == imMessage.lkimDirect) {
                        val accountTable = AccountDao.getInstance().queryById(imMessage.fromAccount)
                        showTxt = String.format(Locale.CHINESE, "%s%s：", showTxt, if (null == accountTable) "" else accountTable!!.nick)
                    }
                } else {
                }
            }
            val content: String
            val draftText = imConversation.getAttribute(IMExtKey.EXTKEY_DRAFTTEXT, "").trim { it <= ' ' }
            if (!TextUtils.isEmpty(draftText)) {
                showTxt = LKStringUtil.getString(R.string.string_im_draft)
                content = draftText
            } else {
                when (imMessage.lkimType) {
                    LKIMType.TXT -> {
                        val lkIMBody = imMessage.lkIMBody as LKIMTxtBody
                        content = lkIMBody.message
                    }
                    LKIMType.VOICE -> content = LKStringUtil.getString(R.string.string_imbody_voice)
                    LKIMType.IMAGE -> content = LKStringUtil.getString(R.string.string_imbody_image)
                    LKIMType.FILE -> content = LKStringUtil.getString(R.string.string_imbody_file)
                    LKIMType.LOCATION -> content = LKStringUtil.getString(R.string.string_imbody_location)
                    LKIMType.VIDEO -> content = LKStringUtil.getString(R.string.string_imbody_video)
                    else -> content = " "
                }
            }
            showTxt = String.format(Locale.CHINESE, "%s%s", showTxt, content)
        } else {
            val draftText = imConversation.getAttribute(IMExtKey.EXTKEY_DRAFTTEXT, "").trim { it <= ' ' }
            if (!TextUtils.isEmpty(draftText)) {
                showTxt = String.format(Locale.CHINESE, "%s%s", LKStringUtil.getString(R.string.string_im_draft), draftText)
            }
        }
        val spannableString = ParseEmojiOperate.getInstance().parseEmoji(showTxt, 20)//Emoji解析
        val draft = LKStringUtil.getString(R.string.string_im_draft)
        if (spannableString.length > 6) {
            val draftCS = spannableString.subSequence(0, 4)
            if (TextUtils.equals(draft, draftCS)) {
                spannableString.setSpan(ForegroundColorSpan(Color.parseColor("#EA6262")), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            } else {
//                val attention = LKStringUtil.getString(R.string.string_im_attention)
//                val specialRemind = LKStringUtil.getString(R.string.string_im_specialRemind)
//                val charSequence = spannableString.subSequence(0, 6)
//                if (TextUtils.equals(attention, charSequence) || TextUtils.equals(specialRemind, charSequence)) {
//                    spannableString.setSpan(ForegroundColorSpan(Color.parseColor("#4390E1")), 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
//                }
            }
        } else if (spannableString.length > 4) {
            val draftCS = spannableString.subSequence(0, 4)
            if (TextUtils.equals(draft, draftCS)) {
                spannableString.setSpan(ForegroundColorSpan(Color.parseColor("#EA6262")), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            }
        }


        return spannableString
    }

    /**
     * 初始化聊天适配器子条目长按后弹窗
     * 0.通知 1.文字 2.语音 3.图片 4.链接 5.短视频 6.自定义表情 7.位置 8.名片 9.文件
     *
     * @param lkimMessage
     * @return
     */
    fun initIMAdapterDialog(lkimMessage: LKIMMessage): List<DialogListView.DialogListObj> {
        val dialogListObjs = ArrayList<DialogListView.DialogListObj>()
        if (LKIMStatus.SUCCESS == lkimMessage.lkimStatus) {
            /*所有选项源*/
            val typeDes = LKStringUtil.getStringArray(R.array.string_im_operateItem)
           val messgeType= getMsgType(lkimMessage)
            if (LKIMDirect.RECEIVE == lkimMessage.getLKIMDirect()) {
                when(messgeType){
                    SkKey.BTKEY_INT_1->{
                        addItemData(dialogListObjs, typeDes, SkKey.BTKEY_INT_0, SkKey.BTKEY_INT_2)
                    }
                    SkKey.BTKEY_INT_2->{
                        val isOutSide = LKSPUtil.getInstance(SP_NAME).getBoolean(KEY_VOICEPLAY_ISOUTSIDE)
                        val playType = if (isOutSide) SkKey.BTKEY_INT_4 else SkKey.BTKEY_INT_5
                        addItemData(dialogListObjs, typeDes,SkKey.BTKEY_INT_2, playType)
                    }
                    SkKey.BTKEY_INT_3->{
                        addItemData(dialogListObjs, typeDes,  SkKey.BTKEY_INT_2)
                    }
                    SkKey.BTKEY_INT_5->{
                        addItemData(dialogListObjs, typeDes,  SkKey.BTKEY_INT_2)
                    }
                }
            }else{
                when(messgeType){
                    SkKey.BTKEY_INT_1->{
                        addItemData(dialogListObjs, typeDes, SkKey.BTKEY_INT_0, SkKey.BTKEY_INT_2, SkKey.BTKEY_INT_3)
                    }
                    SkKey.BTKEY_INT_2->{
                        val isOutSide = LKSPUtil.getInstance(SP_NAME).getBoolean(KEY_VOICEPLAY_ISOUTSIDE)
                        val playType = if (isOutSide) SkKey.BTKEY_INT_4 else SkKey.BTKEY_INT_5
                        addItemData(dialogListObjs, typeDes,  SkKey.BTKEY_INT_2, SkKey.BTKEY_INT_3,playType)
                    }
                    SkKey.BTKEY_INT_3->{
                        addItemData(dialogListObjs, typeDes,  SkKey.BTKEY_INT_2, SkKey.BTKEY_INT_3)
                    }
                    SkKey.BTKEY_INT_5->{
                        addItemData(dialogListObjs, typeDes,  SkKey.BTKEY_INT_2, SkKey.BTKEY_INT_3)
                    }
                }
            }
        } else {
            dialogListObjs.add(DialogListView.DialogListObj(SkKey.BTKEY_INT_2, LKStringUtil.getString(R.string.string_im_delete)))
        }
        return dialogListObjs
    }

    fun getMsgType(lkimMessage: LKIMMessage):Int{
        val mesgType = lkimMessage.getAttribute(IMExtKey.EXTKEY_MESSAGETYPE, SkKey.BTKEY_String_1)
        if (TextUtils.equals(mesgType, SkKey.BTKEY_String_0)) {
            return 0
        } else if (TextUtils.equals(mesgType, SkKey.BTKEY_String_1)) {
            return 1
        } else if (TextUtils.equals(mesgType, SkKey.BTKEY_String_2)) {
            return 2
        } else if (TextUtils.equals(mesgType, SkKey.BTKEY_String_3)) {
            return 3
        }  else if (TextUtils.equals(mesgType, SkKey.BTKEY_String_5)) {
            return 5
        } else {
            return 1
        }

    }


    /**
     * 添加条目数据
     *
     * @param dialogListObjs
     * @param itemTypes
     */
    private fun addItemData(dialogListObjs: MutableList<DialogListView.DialogListObj>, typeDes: Array<String>, vararg itemTypes: Int) {
        if (null != itemTypes && itemTypes.size > 0) {
            for (itemType in itemTypes) {
                dialogListObjs.add(DialogListView.DialogListObj(itemType, typeDes[itemType]))
            }
        }
    }

    /**
     * 会话列表数据处理
     */
    abstract class ConversationInter {
        abstract fun success(imConversations: List<LKIMConversation>)

        abstract fun faile()

        fun privateMessageCount(privateMessageCount: Int) {}
    }




}